package com.chesnutconsulting.otbasket.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.artesia.entity.TeamsIdentifier;
import com.chesnutconsulting.otbasket.image.finder.artesia.OtBasketConfiguration;
import com.chesnutconsulting.otbasket.image.finder.artesia.OtImageFinder;
import com.chesnutconsulting.otbasket.image.watermark.WatermarkedImageCreator;
import com.chesnutconsulting.otbasket.mail.Emailer;
import com.chesnutconsulting.otbasket.mail.ImageInfoAtom;

@Controller
@RequestMapping("/send")
public class EmailSendController implements InitializingBean {

	private Emailer emailer;
	
	@Autowired
	private String fromAddress;
	
	private OtImageFinder otImageFinder;
	
	private WatermarkedImageCreator wmImageCreator;
	
	private OtBasketConfiguration otBasketConfig;
	
	public EmailSendController ()
	{
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public String sendEmail(ModelMap model, HttpServletRequest request) {

		Enumeration<String> attrNamesEnum = request.getParameterNames();
        ArrayList<String> attrNames = Collections.list(attrNamesEnum);
        Collections.sort(attrNames);
        
		List < ImageInfoAtom > imageInfoAtoms = new ArrayList<ImageInfoAtom>();
		
		String sendAsHtml = request.getParameter("sendAsHtml");
		
		String fromFormElem = request.getParameter("from");

		System.out.println("Checking metadata");
		for ( String attrName: attrNames )
		{
//			String attrName = attrNames.nextElement();

			System.out.println("Checking: " + attrName);
			
			// Get data by asset
			if ( attrName.startsWith("assetId"))
			{
				System.out.println("Found asset: " + attrName);

				String assetIndex = attrName.substring(8, attrName.length());
				String assetId = request.getParameter("assetId-" + assetIndex);
				String comment = request.getParameter("comment-" + assetIndex);
				
				ImageInfoAtom atom = new ImageInfoAtom(null);
				File image = otImageFinder.getImage(assetId);
				atom.setImageFileName(image.getName());
				List<File> img = new ArrayList<File>();
				img.add(image);
				List<File> watermarkedFiles = wmImageCreator.watermark(img);
				atom.setWatermarkedImageFile(watermarkedFiles.get(0));

				Enumeration<String> attrNamesEnum1 = request.getParameterNames();
		        ArrayList<String> attrNames1 = Collections.list(attrNamesEnum1);
		        Collections.sort(attrNames1);
		        
				Map < String, String > metadataMap = new LinkedHashMap<String, String> ();
//				Map < String, String > tmpMetadataMap = new HashMap<String, String> ();
				
				atom.setComment(comment);
				atom.setAssetId(assetId);
				
				System.out.println("Getting metadata for this asset [" + assetIndex + "]");
				for ( String attrName1: attrNames1 )
				{
//					String attrName1 = attrNames1.nextElement();

					// Get fields for asset
					System.out.println("Checking field " + attrName1);
					if ( attrName1.startsWith("field-" + assetIndex))
					{
						System.out.println("Found metadata: " + attrName1);

						String fieldIndex = attrName1.substring(("field-" + assetIndex).length() + 1, attrName1.length());

						System.out.println("Getting metadata [" + fieldIndex + "]");

						String fieldIndexKey = "field-" + assetIndex + ":" + fieldIndex;
						String fieldValueKey = "value-" + assetIndex + ":" + fieldIndex;

						System.out.println("Adding field: value to map: " + request.getParameter(fieldIndexKey) + ": " + request.getParameter(fieldValueKey));

						metadataMap.put(request.getParameter(fieldIndexKey), request.getParameter(fieldValueKey));
						
					}
				}
/*
				for(TeamsIdentifier field: otBasketConfig.getScalarFieldList())
				{
					String fieldStr = tmpMetadataMap.get(field.asString());
					
					if (fieldStr != null && fieldStr.trim().length() > 0)
					{
						metadataMap.put(field.asString(), fieldStr);
					}
				}
*/
				atom.setMetadata(metadataMap);
				imageInfoAtoms.add(atom);
			}
		}
/*		
		List<File> images = new ArrayList<File>();
		for (ImageInfoAtom imageInfoAtom : imageInfoAtoms) {
			String assetId = imageInfoAtom.getAssetId();
			File image = otImageFinder.getImage(assetId);
			images.add(image); 
		}
		
		List<File> watermarkedFiles = wmImageCreator.watermark(images);
		for (int i = 0; i < watermarkedFiles.size(); i++) {
			imageInfoAtoms.get(i).setWatermarkedImageFile(watermarkedFiles.get(i));
		}
*/		
		String toAddresses = request.getParameter("toAddresses");
		StringTokenizer stok = new StringTokenizer(toAddresses, ";");
		List<String> toAddrList = new ArrayList<String>();
		while ( stok.hasMoreTokens() )
		{
			String addr = stok.nextToken();
			toAddrList.add(addr);
		}
		
		System.out.println("Sending email body [" + request.getParameter("body") );
		emailer.emailBasket(imageInfoAtoms, request.getParameter("subject"), request.getParameter("body"), toAddrList, fromAddress, (sendAsHtml!=null)?true:false, fromFormElem );
		
		return "processComplete";

	}

	public Emailer getEmailer() {
		return emailer;
	}

	public void setEmailer(Emailer emailer) {
		this.emailer = emailer;
	}

	public String getFromAddress() {
		return fromAddress;
	}

	public void setFromAddress(String fromAddress) {
		this.fromAddress = fromAddress;
	}

	public OtImageFinder getOtImageFinder() {
		return otImageFinder;
	}

	public void setOtImageFinder(OtImageFinder otImageFinder) {
		this.otImageFinder = otImageFinder;
	}

	public WatermarkedImageCreator getWmImageCreator() {
		return wmImageCreator;
	}

	public void setWmImageCreator(WatermarkedImageCreator wmImageCreator) {
		this.wmImageCreator = wmImageCreator;
	}

	public OtBasketConfiguration getOtBasketConfig() {
		return otBasketConfig;
	}

	public void setOtBasketConfig(OtBasketConfiguration otBasketConfig) {
		this.otBasketConfig = otBasketConfig;
	}

	public void afterPropertiesSet() throws Exception {
		wmImageCreator = new WatermarkedImageCreator(otBasketConfig);		
	}

	
}
